package com.yhy.manager.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhy.manager.domain.Admin;

import com.yhy.manager.exception.BusinessException;
import com.yhy.manager.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    private static final String CACHE_KEY_TOKEN_PREFIX="MANAGE_TOKEN_";

    private static final String CACHE_KEY_CAP_PREFIX = "MANAGE_CAP_";

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //根据token，从redis获取当前管理员数据
    //根据登录token，获取用户对象
    public Admin findUserByToken(String token) {
        String userStr = redisTemplate.opsForValue().get("MANAGE_TOKEN_"+token);
        if(userStr == null) {
            return null;
        }
        return JSON.parseObject(userStr,Admin.class);
    }

    public void saveCap(String uuid, String code) {
        String key = "CACHE_KEY_CAP_PREFIX_"+uuid;
        redisTemplate.opsForValue().set(key,code,Duration.ofMinutes(1));
    }

    public ResponseEntity login(Map map) {
        //1.获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //2.判断用户名密码是否为空
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new BusinessException("用户名或密码为空!");
        }
        //3.判断验证码是否为空
        if(StringUtils.isEmpty(verificationCode)){
            throw new BusinessException("验证码为空!");
        }
        //4.根据用户名查用户
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        //5.判断用户是否存在,密码是否一致
        password = SecureUtil.md5(password);
        if(admin == null || !admin.getPassword().equals(password)){
            throw new BusinessException("用户名或密码错误!");
        }
        //6.通过jwt生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",username);
        claims.put("id",admin.getId());
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256,"itcast")
                .compact();
        //7.将admin存入redis中
        String adminStr = JSON.toJSONString(admin);
        redisTemplate.opsForValue().set(CACHE_KEY_TOKEN_PREFIX+token,adminStr,Duration.ofHours(1));
        //8.构造返回值
        Map res = new HashMap<>();
        res.put("token",token);
        return ResponseEntity.ok(res);
    }

    //登出方法 删除redis中的数据
    public ResponseEntity logout(String token) {
        token = token.replaceAll("Bearer ","");
        String adminKey = CACHE_KEY_TOKEN_PREFIX+token;
        redisTemplate.delete(adminKey);
        return ResponseEntity.ok(null);
    }
}
